package org.zoomdev.zoom.dao.ddl.utils;


import org.zoomdev.zoom.common.utils.MapUtils;
import org.zoomdev.zoom.dao.meta.TableMeta;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public final class IncrementUtils {

    /**
     * @param fromClasses   比较新
     * @param databaseMetas
     * @return
     */
    public static List<String> incSql(List<TableMeta> fromClasses, List<TableMeta> databaseMetas) {
        Map<String, TableMeta> older = MapUtils.toMap(databaseMetas, i -> i.getName().toUpperCase());
        return compare(fromClasses, older);
    }

    public static List<String> diffSql(List<TableMeta> fromClasses, List<TableMeta> databaseMetas) {
        Map<String, TableMeta> older = MapUtils.toMap(fromClasses, i -> i.getName().toUpperCase());
        return compare(databaseMetas, older);
    }

    private static List<String> compare(List<TableMeta> newer, Map<String, TableMeta> older) {
        List<String> sqlList = new ArrayList<>();
        for (TableMeta fromClass : newer) {
            TableMeta fromDatabase = older.get(fromClass.getName().toUpperCase());
            if (fromDatabase == null) {
                String sql = MetaCreate.generateCreate(fromClass, true, false);
                sqlList.add(sql);
            } else {
                List<String> sql = MetaIncrement.getIncrements(fromClass, fromDatabase);
                sqlList.addAll(sql);
            }
        }
        return sqlList;
    }
}
